package com.woniu.zsd.merchant.onterceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
@Configuration
public class FeignTokenInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        HttpServletRequest request = getHttpServletRequest();
        if (request == null) return;

        // 动态获取当前请求中的 Authorization 头
        String token = request.getHeader("Authorization");

        // 将 token 传递给下游 Feign 请求
        if (token != null && !token.isEmpty()) {
            template.header("Authorization", token);
        }
    }

    // 从当前线程上下文中获取 HTTP 请求
    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes)
                    RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }
}
